package com.innjia.base.utils;

import com.xiaoleilu.hutool.util.ImageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.function.Function;

/**
 * 图片处理工具类
 * <br>
 * 2017-11-30
 *
 * @author zhouxianglh@gmail.com
 */
public class ImageUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ImageUtils.class);

    private static final String FLAG = "盈家生活";

    private static Font font = new Font("SERIF", Font.BOLD, 72);

    //    public static void main(String[] args) throws Exception {
    //        byte[] image = FileUtils.readFileToByteArray(new File("C:\\Users\\zhoux\\Desktop\\a.jpg"));
    //        image = scaleImage(image, 0.5f);
    //        FileUtils.writeByteArrayToFile(new File("C:\\Users\\zhoux\\Desktop\\b.jpg"), image);
    //    }

    /**
     * 压缩图片(拉,伸),并添加水印
     *
     * @param image
     * @param size
     * @return
     */
    public static byte[] scaleImage(byte[] image, float size) {
        return scaleImage(image, scrImage -> ImageUtil.scale(scrImage, size));
    }

    /**
     * 压缩图片(拉,伸),并添加水印
     *
     * @param image
     * @param function
     * @return
     */
    private static byte[] scaleImage(byte[] image, Function<Image, Image> function) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            Image newImage = function.apply(ImageIO.read(new ByteArrayInputStream(image)));
            ImageUtil.pressText(newImage, ImageIO.createImageOutputStream(outputStream), FLAG, Color.ORANGE, font, 0, 0, 0.2f);
            return outputStream.toByteArray();
        } catch (IOException e) {
            LOGGER.error("", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 压缩图片(拉,伸),并添加水印
     *
     * @param image
     * @param width
     * @param height
     * @return
     */
    public static byte[] scaleImage(byte[] image, int width, int height) {
        return scaleImage(image, scrImage -> ImageUtil.scale(scrImage, width, height));
    }
}
